import { useState } from "react";
import errorCode from "./errorCode";
import { fetchRequest } from "./Request";
import { url } from "./url";
import { Redirect, Route } from "react-router";
import Loading from "../components/Loading/Loading.jsx";
import { useRequest } from "@umijs/hooks";

export default function PermissionRouter(props: any) {
  const [state, setstate] = useState({
    loginCode: errorCode.NOT_LOGIN,
  });

  async function getRoutes() {
    try {
      const json = await fetchRequest(url.CHECK_LOGIN_URL, "");
      if (json.success) {
        setstate({ loginCode: errorCode.LOGIN_SUCCESS });
      } else {
        setstate({ loginCode: json.code });
      }
    } catch (error: any) {
      setstate({ loginCode: errorCode.LOGIN_FAIL });
    }
  }

  const data = useRequest(getRoutes, {
    loadingDelay: 500,
  });

  const { component: Component, ...rest } = props;
  switch (state.loginCode) {
    case errorCode.LOGIN_OUT_DATE:
      return <Redirect to="/nologin" />;

    case errorCode.LOGIN_FAIL:
      return <Redirect to="/nologin" />;

    case errorCode.NO_PERMISSION:
      return <Redirect to="/nopermission" />;

    case errorCode.LOGIN_SUCCESS:
      return (
        <Route
          {...rest}
          render={(props) => {
            return <Component {...props} />;
          }}
        />
      );

    default:
      if (data.loading) return <Loading />;
      else {
        return null;
      }
  }
}
